package com.wl.api.service.business.impl;

import static com.wl.api.common.utils.PageInfo.transformPage;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.wl.api.dto.business.CustomerUserGradeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wl.api.common.utils.BeanUtils;
import com.wl.api.common.utils.PageInfo;
import com.wl.api.common.utils.StringUtil;
import com.wl.api.dto.business.CustomerUserDTO;
import com.wl.api.mapper.business.CustomerUserMapper;
import com.wl.api.model.business.CustomerUser;
import com.wl.api.model.system.SecurityGrade;
import com.wl.api.service.business.ICustomerUserService;
import com.wl.api.service.system.ISecurityGradeService;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * CustomerUser 表数据服务层接口实现类
 *
 */
@Service
public class CustomerUserServiceImpl extends ServiceImpl<CustomerUserMapper, CustomerUser> implements ICustomerUserService {

	@Autowired
	ISecurityGradeService securityGradeService;
	
	public CustomerUser getCustomerUser(CustomerUserDTO param) {
		
		return selectOne(new EntityWrapper<CustomerUser>(BeanUtils.copyProperties(param, CustomerUser.class))) ;
	}
	
	@Override
	public PageInfo<CustomerUserDTO> getCustomerUserPage(CustomerUserDTO param) {
		Wrapper<CustomerUser> wrapper = new EntityWrapper<CustomerUser>().where(" 1=1 ");

		if (!StringUtil.isEmpty(param.getUsername())) {
			wrapper.andNewSimple("username",  param.getUsername());
		}

		Page<CustomerUser> page = selectPage(new Page<>(param.getPage(), param.getPageSize(), "update_time", false), wrapper);
		
		PageInfo<CustomerUserDTO> pageInfo  = transformPage(CustomerUserDTO.class, page);
		if (!Objects.isNull(page) && page.getTotal() > 0) {
			List<SecurityGrade> gradeList = securityGradeService.selectBatchIds(page.getRecords().parallelStream().map(CustomerUser::getGradeId).distinct().collect(Collectors.toList()));
			Map<Long, String> map = gradeList.parallelStream().collect(Collectors.toMap(SecurityGrade::getId, SecurityGrade::getName));
			for (CustomerUserDTO dd: pageInfo.getItems()) {
				dd.setGradeName(map.get(dd.getGradeId()));
			}
		}
		return pageInfo;
	}

	@Transactional
	@Override
	public void batchUpdateCustomerByIds(CustomerUserGradeDTO param) {
		update(CustomerUser.builder().updateTime(new Date()).updateUserId(param.getUpdateUserId()).build(), new EntityWrapper<CustomerUser>().in("cust_id", param.getUserIds()));
	}
}